#include "MarsPrecompile.h"

#include "MarsShaderMgr.h"
#include "MarsVertexShader.h"
#include "MarsPixelShader.h"

using namespace Graphics;

ShaderMgr* ShaderMgr::ms_pShaderMgr = 0;

void ShaderMgr::Destroy()
{
	SAFE_DELETE( ms_pShaderMgr );
}

ShaderMgr::ShaderMgr()
{

}

ShaderMgr::~ShaderMgr()
{
	Shutdown();
}

bool ShaderMgr::Initialize()
{
	return true;
}

void ShaderMgr::Shutdown()
{
	ShaderMapItr it = m_mapShaders.begin();
	ShaderMapItr end = m_mapShaders.end();

	for ( ; it != end; ++it )
	{
		SAFE_DELETE( it->second );
	}

	m_mapShaders.clear();
}

Shader* ShaderMgr::LoadShader( ShaderType eType, const char* pcszFileName, const char* pcszEntry, const char* pcszShaderModel )
{
	std::string str = pcszFileName;
	str += pcszEntry;
	Core::uint32 iHash = StrCRC::CRC( str );

	if ( m_mapShaders.find( iHash ) != m_mapShaders.end() )
		return m_mapShaders[ iHash ];

	Shader* pShader = NULL;
	if ( eType == ShaderType_Vertex )
		pShader = new VertexShader( pcszFileName, pcszEntry, pcszShaderModel );
	else if ( eType == ShaderType_Pixel )
		pShader = new PixelShader( pcszFileName, pcszEntry, pcszShaderModel );
	
	MARS_ASSERT( pShader );

	if ( !m_shaderCompiler.CompileShader( *pShader ) )
	{
		SAFE_DELETE( pShader );
		return NULL;
	}

	if ( !pShader->PostCompile() )
	{
		SAFE_DELETE( pShader );
		return NULL;
	}

	m_mapShaders.insert( std::make_pair( pShader->GetHash(), pShader ) );

	return pShader;
}
